<?php
/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 19-5-13 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\controllers;

use Yii;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\web\Response;

/**
 * 后台认证控制器
 * Authenticator controller
 */
class AuthAdminController extends BaseController
{
    public $serializer = [
        'class' => 'yii\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    /**
     * 绑定规则的权限如需要传送参数，请在对应action处手动调用验证, 如【roleDelete】删除角色：
     * Yii::$app->getUser()->can(控制器名+动作名, [参数])
     */
    public $whiteAction = ['roleDelete']; // 白名单 控制器名+动作名(不含前缀action)

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::class,
            'authMethods' => [
                //配置API接口认证方式
                HttpBearerAuth::class
            ],
        ];
        // HTTP 头发送目前的速率限制信息
        $behaviors['rateLimiter']['enableRateLimitHeaders'] = false;
        return $behaviors;
    }

    /**
     * @param $action
     * @return mixed
     * @throws \Throwable
     */
    public function beforeAction($action)
    {
        parent::beforeAction($action);
        $user = Yii::$app->getUser()->getIdentity();
        if (empty($user->group_id)) {
            Yii::$app->response->data = Yii::$app->api->error('您不是管理员');
            return false;
        }

        $cs = explode('-', $action->controller->id);
        foreach ($cs as $k => &$c) {
            if ($k == 0) {
                $c = lcfirst($c);
            } else {
                $c = ucfirst($c);
            }
        }
        $actions = explode('-', $action->id);
        foreach ($actions as &$item) {
            $item = ucfirst($item);
        }
        $ac = join('', $cs) . ucfirst(join('', $actions));
        if (!in_array($ac, $this->whiteAction) && !Yii::$app->getUser()->can($ac)) {
            Yii::$app->response->data = Yii::$app->api->error('您无查看或操作权限: ' . $ac);
            return false;
        }
        return true;
    }

    /**
     * 检测post请求
     * 如果非post请求，发送4405代码
     * @return mixed
     */
    public function validateIsPost()
    {
        if (!Yii::$app->getRequest()->getIsPost()) {
            $response = Yii::$app->getResponse();
            $response->data = Yii::$app->api->send(4405);
            $response->send();
        }
        return true;
    }
    /**
     * 退出
     * @return mixed
     * @throws \Throwable
     */
    public function actionLogout()
    {
        $user = Yii::$app->getUser()->getIdentity();
        $user->access_token_expire = 0;
        $user->update(false, ['access_token_expire']);
        return Yii::$app->api->success();
    }
}
